import React from 'react';
import type { JSONTemplateFormItemInterface } from '@/components/CustomElement/JSONTemplateForm/interface';
import {
    ProFormCheckbox,
    ProFormDatePicker,
    ProFormDateRangePicker,
    ProFormDateTimePicker,
    ProFormDateTimeRangePicker,
    ProFormDigit,
    ProFormRadio,
    ProFormSelect,
    ProFormSwitch,
    ProFormText,
    ProFormTextArea,
    ProFormTimePicker,
} from '@ant-design/pro-form';

// 类型映射
const ItemMap = {
    Text: ProFormText,
    Password: ProFormText.Password,
    DatePicker: ProFormDatePicker,
    DateTimePicker: ProFormDateTimePicker,
    DateRangePicker: ProFormDateRangePicker,
    DateTimeRangePicker: ProFormDateTimeRangePicker,
    TimePicker: ProFormTimePicker,
    TextArea: ProFormTextArea,
    Checkbox: ProFormCheckbox,
    Radio: ProFormRadio.Group,
    Switch: ProFormSwitch,
    Select: ProFormSelect,
    Digit: ProFormDigit,
};

const TemplateFormItem: React.FC<JSONTemplateFormItemInterface> = (props) => {
    const {
        type,
        label,
        extra,
        name,
        readonly,
        disabled,
        value,
        options,
        itemKey,
        namePrefix,
        ...rest
    } = props;

    const filedProps = {
        label,
        extra,
        name: namePrefix ? [namePrefix, name] : name,
        readonly,
        disabled,
        value,
        options,
        ...rest,
    };

    const Field = ItemMap[type] as any;

    if (!Field) {
        return (
            <div key={itemKey} className={'text-danger'}>
                Unknown form item config!
            </div>
        );
    }

    const renderChildren = () => {
        return <div key={itemKey}>{React.createElement(Field, filedProps)}</div>;
    };

    return renderChildren();
};

export default TemplateFormItem;
